package edu.gatech.cs2340.aperturescience;

import java.io.IOException;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

/**
 * 
 * @author Jacob Morgan, Kefu Zhou, Kevin Lacey, Kelly Evanish
 * 
 *         Creating new account and accessing the database to store registered
 *         users.
 */

public class UserList extends ListActivity {
	private final String dbName = "UserList";
	private final String dbTable = "Users";

	SQLiteDatabase myDB = null;

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		try {
			this.openOrCreateDatabase(dbName, 1, null);
			myDB = this.openOrCreateDatabase(dbName, 1, null);

			myDB.execSQL("CREATE TABLE IF NONE EXISTS " + dbTable
					+ " (Username VARCHAR, Password VARCHAR, Email VARCHAR, "
					+ "LastName VARCHAR, FirstName VARCHAR, Date INT(5));");
		} finally {
			if (myDB != null)
				myDB.close();
		}
	}

	/**
	 * Checks whether the username is valid.
	 * 
	 * @param username the username
	 * 
	 * @param password the password
	 * 
	 * @return exists boolean value
	 */
	public boolean checkUsername(String username, String password)
			throws IOException {
		boolean exists = false;

		myDB = this.openOrCreateDatabase(dbName, 1, null);

		Cursor c = myDB.rawQuery("SELECT Username" + " FROM " + dbTable
				+ " WHERE Username == username;", null);

		if (c != null) {
			exists = true;
		}

		return exists;

		// Get the indices of the Columns we will need
		// int firstNameColumn = c.getColumnIndex("FirstName");
		// int ageColumn = c.getColumnIndex("Age");
	}

	/**
	 * Creates new user.
	 * 
	 * @param usernmae
	 *            user's username
	 * 
	 * @param password
	 *            user's password
	 * 
	 * @param email
	 *            user's Email
	 * 
	 * @param lastName
	 *            user's last name
	 * 
	 * @param firstName
	 *            user's first name
	 * 
	 * @return created boolean value for whether account has been create
	 */
	public boolean createNewUser(String username, String password,
			String email, String lastName, String firstName) {
		boolean created = false;

		String values = username + ", " + password + ", " + email + ", "
				+ lastName + ", " + firstName + ", 02272012";

		myDB.execSQL("INSERT INTO " + dbTable
				+ " (Username, Password, Email, LastName, Firstname, Date)"
				+ " VALUES (" + values + ")");

		return created;
	}

}